import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // 引入路由
import { $get } from './utils/request'
import ElementUI from './plugins/elementui.js' // 手动导入element组件
import 'element-plus/dist/index.css' // 引入element ui组件样式
import '@/assets/iconfont/iconfont.css' // 引入阿里云字体图标CSS
import { AuthApi, ConfigApi } from './api/path'
import { SocketIo } from '@/utils/socket.js'
import screenShort from 'vue-web-screen-shot'

const app = createApp(App)
ElementUI(app) // 手动按需加载element ui组件
app.use(router) // 加载路由
app.use(screenShort,{enableWebRtc:false}); // 导入截图插件
const token = localStorage.getItem('token')
// console.log('main, token: ' + token)

// 验证登录的异步函数
const checkLogin = async () => {
    if (!token) {
      // 如果没有 token，跳转到登录页面
      console.log('xxx')
      router.replace('/login');
      return false;
    }
  
    try {
      // 发送请求到后端验证 token 是否有效
      const res = await $get(AuthApi.checkLogin);
      if (res.success && res.data) {
        await loadGlobalConfig();
        initializeSocketIO();
        return true;
      } else {
        console.log('main-checkLogin-res: ', res)
        router.replace('/login');
        return false;
      }
    } catch (error) {
      console.error('登录验证失败:', error);
      router.replace('/login');
      return false;
    }
  };
  
  // 加载全局配置
  const loadGlobalConfig = async () => {
    try {
      const res = await $get(ConfigApi.getWebConfigs);
      if (res.success) {
        window.globalConfig = res.data;
        console.log('全局配置加载成功:', res.data);
      }
    } catch (error) {
      console.error('全局配置加载失败:', error);
    }
  };
  
  // 初始化 socket.io
  const initializeSocketIO = () => {
    console.log('main-init-socket-addr: ' + window.globalConfig.SOCKETIO_ADDR)
    const settings = {
        url: window.globalConfig.SOCKETIO_ADDR,
        connect: ()=>{console.log('connected!')},
        disconnect: ()=>{console.log('disconnected!')},
        pingReceived: ()=>{console.log('pingReceived!')}
      }
      const options = {
        query:{ // 传输token进行授权
          token: localStorage.getItem('token')
        },
        transports: ['websocket'] // 强制使用websocket协议提交效率
      }
      window.socket = new SocketIo(settings, options)
  };
  
  // 检测登录后再进行根组件挂载
  const initApp = async () => {
    const isLoggedIn = await checkLogin();
    if (isLoggedIn) {
      // 如果已登录，挂载根组件
      app.mount('#app');
    }
  };
  
  // 调用初始化方法
  initApp();
